<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 申请人管理（申请人信息）
 */
class Client extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model("client_model");
        $this->load->model("contact_model");
        $this->load->model("document_model");
        $this->load->helper('form');
        $this->load->helper('string');
        $this->load->library('form_validation');
    }
    
    /**
     * 申请人列表
     * @param type $page
     */
    public function index($page = 1)
	{
        $conditions = array(
            'keyword' => trim($this->input->post('keyword')),
        );

        $this->config->load('pagination', true);
        $pagination = $this->config->item('pagination');
        $pagination['base_url'] = site_url('client/index');
        $pagination['total_rows'] = $this->client_model->fetch_count($conditions);
        $this->load->library('pagination', $pagination);
        
        $data = array(
            'title' => '申请人资料 - 申请人列表',
            'operations' => array(
                array('label' => '添加申请人', 'uri' => 'client/create'),
            ),
            'conditions' => $conditions,
            'clients' => $this->client_model->fetch_array($conditions, $pagination['per_page'], $page),
            'pagelink' => $this->pagination->create_links()
        );

		$this->load->view('header', $data);
        $this->load->view('client/list', $data);
        $this->load->view('footer');
	}
    
    /**
     * 添加申请人
     */
    public function create() {
        
        $data = array(
            'title' => '申请人资料 - 添加申请人',
            'operations' => array(
                array('label' => '申请人列表', 'uri' => 'client')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $contacts = $this->_get_form_contacts();
            $documents = $this->_get_form_documents();
            
            $this->_set_form_validation_rules();
            if ($this->form_validation->run()) {
                /* 插入数据 */
                $this->contact_model->insert_batch($contacts);
                
                $client = $this->_get_form_client();
                $client['contact_ids'] = $this->contact_model->insert_ids();
                $this->client_model->insert($client);
                $c_id = $this->client_model->insert_id();
                
                foreach ($documents as $doc) {
                    $doc['relation_id'] = DOC_R_CLIENT . $c_id;
                    $this->document_model->insert($doc);
                }

                $data['sucess_message'] = '您已成功添加了申请人 ' . $client['c_name'];
                $data['operations'][] = array('label' => '再次添加申请人', 'uri' => 'client/create');
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            $documents = array();
            $contacts = array();
        }

        /* 显示添加表单 */
        $data['empty_contact_html'] = $this->_get_empty_contact_html();
        $data['contacts_html'] = $this->_get_contacts_html($contacts);
        $data['empty_document_html'] = $this->_get_empty_document_html();
        $data['documents_html'] = $this->_get_documents_html($documents);
        $data['action'] = 'client/create';
        $data['client'] = $this->client_model->new_client();
        $data['licence_types'] = $this->_licence_type_options();
        $this->load->view('header', $data);
        $this->load->view('client/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 修改申请人
     * @param type $id
     */
    public function update($id) {
        $client = $this->client_model->get($id);
        if (empty($client)) {
            /* 申请人不存在 */
            show_404();
        }
        
        $data = array(
            'title' => '申请人资料 - 修改申请人 - ' . $client['c_name'],
            'operations' => array(
                array('label' => '申请人列表', 'uri' => 'client')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $contacts = $this->_get_form_contacts();
            $documents = $this->_get_form_documents();

            $this->_set_form_validation_rules($id);
            if ($this->form_validation->run()) {
                /* 验证通过，更新数据 */
                $this->contact_model->insert_batch($contacts);
                
                $client = $this->_get_form_client();
                $client['contact_ids'] = $this->contact_model->insert_ids();
                $this->client_model->update($id, $client);
                
                $relation_id = DOC_R_CLIENT . $id;
                $this->document_model->delete_batch_by_relation($relation_id);
                foreach ($documents as $doc) {
                    $doc['relation_id'] = $relation_id;
                    $this->document_model->insert($doc);
                }

                $data['sucess_message'] = '您已成功修改了申请人 ' . $client['c_name'];
                $data['operations'][] = array('label' => '再次修改申请人', 'uri' => 'client/update/' . $id);
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            /* 没有提交数据 */
            $contacts = $this->contact_model->fetch_array(array('ids' => $client['contact_ids']));
            $documents = $this->document_model->fetch_array(array('relation_id' => DOC_R_CLIENT . $id));
        }
        
        /* 显示修改表单 */
        $data['empty_contact_html'] = $this->_get_empty_contact_html();
        $data['contacts_html'] = $this->_get_contacts_html($contacts);
        $data['empty_document_html'] = $this->_get_empty_document_html();
        $data['documents_html'] = $this->_get_documents_html($documents);
        $data['action'] = 'client/update/' . $id;
        $data['client'] = $client;
        $data['licence_types'] = $this->_licence_type_options();
        $this->load->view('header', $data);
        $this->load->view('client/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 查看申请人
     * @param type $id
     */
    public function view($id) {
        $client = $this->client_model->get($id);
        if (empty($client)) {
            /* 申请人不存在 */
            show_404();
        }
        
        $data = array(
            'title' => '申请人资料 - 查看申请人 - ' . $client['c_name'],
            'operations' => array(
                array('label' => '申请人列表', 'uri' => 'client')
            )
        );
        
        $contacts = $this->contact_model->fetch_array(array('ids' => $client['contact_ids']));
        
        /* 显示修改表单 */
        $data['c'] = $client;
        $data['cts'] = $contacts;
        $this->load->view('header', $data);
        $this->load->view('client/view', $data);
        $this->load->view('footer');
    }
    
    /**
     * 删除申请人
     * @param type $id
     */
    public function remove($id) {
        $client = $this->client_model->get($id);
        if (empty($client)) {
            /* 申请人不存在 */
            show_404();
        }
        
        // TODO 判断能否删除
        
        $data = array(
            'title' => '申请人资料 - 删除申请人 - ' . $client['c_name'],
            'operations' => array(
                array('label' => '申请人列表', 'uri' => 'client')
            )
        );
        
        $this->client_model->delete($id);
                
        $data['sucess_message'] = '您已成功删除了申请人 ' . $client['c_name'];
        $this->load->view('header', $data);
        $this->load->view('footer');

    }
    
    /**
     * 取官方文件html
     * @return string
     */
    private function _get_empty_document_html() {
        return trim_line_break($this->load->view('client/document', '', true));
    }
    private function _get_documents_html($documents) {
        $html = '';
        foreach ($documents as $document) {
            $html .= trim_line_break($this->load->view('client/document', array('document' => $document), true));
        }

        return $html;
    }
    
    /**
     * 从表单取官方文件
     */
    private function _get_form_documents() {
        $in = $this->input;

        if ($in->post('doc_name') == FALSE) {
            return array();
        }
        
        $doc_names         = $in->post('doc_name');
        $doc_paths         = $in->post('doc_path');
        $doc_original_name = $in->post('doc_original_name');
        
        $documents = array();
        $count = count($in->post('doc_name'));
        for ($i = 0; $i < $count; $i++) {
            $documents[] = array(
                'doc_name'          => $doc_names[$i],
                'doc_path'          => $doc_paths[$i],
                'doc_original_name' => $doc_original_name[$i],
            );
        }
        
        return $documents;
    }

    /**
     * 取联系信息html
     * @return type
     */
    private function _get_empty_contact_html() {
        return trim_line_break($this->load->view('client/contact', '', true));
    }
    private function _get_contacts_html($contacts) {
        $html = '';
        foreach ($contacts as $contact) {
            $html .= trim_line_break($this->load->view('client/contact', array('contact' => $contact), true));
        }

        return $html;
    }

    /**
     * 从表单取申请人信息
     * @return array
     */
    private function _get_form_client() {
        $in = $this->input;
        
        return array(
            'c_name' => $in->post('c_name'),
            'c_name_en' => $in->post('c_name_en'),
            'c_addr' => $in->post('c_addr'),
            'c_addr_en' => $in->post('c_addr_en'),
            'c_mailing_addr' => $in->post('c_mailing_addr'),
            'c_mailing_addr_en' => $in->post('c_mailing_addr_en'),
            'c_licence_type' => $in->post('c_licence_type'),
            'c_licence_number' => $in->post('c_licence_number'),
            'c_country' => $in->post('c_country'),
        );
    }
    
    /**
     * 从表单取联系信息
     * @return array
     */
    private function _get_form_contacts() {
        $in = $this->input;

        if ($in->post('ct_contact') == FALSE) {
            return array();
        }
        
        $ct_contacts    = $in->post('ct_contact');
        $ct_positions   = $in->post('ct_position');
        $ct_telephones  = $in->post('ct_telephone');
        $ct_faxs        = $in->post('ct_fax');
        $ct_qqs         = $in->post('ct_qq');
        $ct_others      = $in->post('ct_other');
        
        $contacts = array();
        $count = count($in->post('ct_contact'));
        for ($i = 0; $i < $count; $i++) {
            $contacts[] = array(
                'ct_contact'    => $ct_contacts[$i],
                'ct_position'   => $ct_positions[$i],
                'ct_telephone'  => $ct_telephones[$i],
                'ct_fax'        => $ct_faxs[$i],
                'ct_qq'         => $ct_qqs[$i],
                'ct_other'      => $ct_others[$i],
            );
        }
        
        return $contacts;
    }


    /**
     * 返回 证照类型 下拉列表的options
     * @return type
     */
    private function _licence_type_options() {
        $options = array('' => '');
        foreach ($this->client_model->licence_types() as $type) {
            $options[$type] = $type;
        }
        return $options;
    }
    
    /**
     * 设置表单验证规则
     */
    private function _set_form_validation_rules($id = 0) {
        $fv = $this->form_validation;
        $fv->set_rules('c_name', '名称（中文）', "trim|required|is_unique[clients.c_name.c_id.$id]");
        $fv->set_rules('c_addr', '地址（中文）', 'trim|required');
        $fv->set_rules('c_licence_type', '证照类型', 'required');
        $fv->set_rules('c_licence_number', '证照编号', "trim|required|is_unique[clients.c_licence_number.c_id.$id]");
        
        $fv->set_rules('c_name_en', '', 'trim');
        $fv->set_rules('c_addr_en', '', 'trim');
        $fv->set_rules('c_mailing_addr', '', 'trim');
        $fv->set_rules('c_mailing_addr_en', '', 'trim');
        $fv->set_rules('c_country', '', 'trim');
    }
}

